package cn.wolfcode.service.impl;

import cn.wolfcode.domain.Department;
import cn.wolfcode.domain.Employee;
import cn.wolfcode.mapper.EmployeeMapper;
import cn.wolfcode.qo.PageResult;
import cn.wolfcode.qo.QueryObject;
import cn.wolfcode.service.IEmployeeService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.Collections;
import java.util.List;

@Service
public class EmployeeServiceImpl implements IEmployeeService {

    @Resource
    private EmployeeMapper employeeMapper;

    @Override
    public void save(Employee employee, Long[] ids) {
        //对密码进行加密,使用用户名作为盐
        Md5Hash md5Hash = new Md5Hash(employee.getPassword(), employee.getName());
        employee.setPassword(md5Hash.toString());

        employeeMapper.insert(employee);

        if (ids != null && ids.length > 0) {
            employeeMapper.roleRelation2(employee.getId(), ids);

        }

    }

    @Override
    public void delete(Long id) {
        employeeMapper.deleteByPrimaryKey(id);
    }

    @Override
    public void update(Employee employee, Long[] ids) {
        employeeMapper.updateByPrimaryKey(employee);
        //删除原来的关系
        employeeMapper.deleteRelation(employee.getId());
        if (ids != null && ids.length > 0) {
            //处理中间表
            for (Long roleId : ids) {
                employeeMapper.insertRelation(employee.getId(), roleId);
            }
        }
    }

    @Override
    public Employee get(Long id) {
        return employeeMapper.selectByPrimaryKey(id);
    }

    @Override
    public List<Employee> listAll() {
        return employeeMapper.selectAll();
    }

    //分页查询
    @Override
    public PageInfo<Employee> query(QueryObject qo) {
        //使用分页插件,传入当前页,每页显示数量
        PageHelper.startPage(qo.getCurrentPage(), qo.getPageSize());
        List<Employee> employees = employeeMapper.selectForList(qo);
        return new PageInfo(employees);
    }

    @Override
    public Employee login(String username, String password) {

        if (!StringUtils.hasLength(username)) {
            throw new RuntimeException("用户名不能为空");
        }
        if (!StringUtils.hasLength(password)) {
            throw new RuntimeException("密码不能为空");
        }

        Employee employee = employeeMapper.selectByUsernameAndPassword(username, password);
        if (employee == null) {
            throw new RuntimeException("用户名和密码不匹配");
        }
        return employee;
    }

    @Override
    public Employee selectPassword(Long id, String oldPassword) {
        Employee employee = employeeMapper.selectByPassword(id, oldPassword);
        if (employee == null) {
            throw new RuntimeException("原密码错误");
        }

        return employee;
    }

    @Override
    public void updatePassword(Long id, String newPassword) {
        employeeMapper.updateByPassword(id, newPassword);
    }

    @Override
    public void batchDelete(Long[] ids) {
        this.employeeMapper.batchDelete(ids);
    }

    @Override
    public Employee selectByName(String name) {
        return this.employeeMapper.selectByName(name);
    }

    /**
     * 导出为excel
     *
     * @return
     */
    @Override
    public Workbook exportxls() {
        //创建excel文件
        Workbook wb = new HSSFWorkbook();
        //创建sheet
        Sheet sheet = wb.createSheet("员工名单");
        //标题行
        Row row = sheet.createRow(0);
        //设置内容到单元格中
        row.createCell(0).setCellValue("姓名");
        row.createCell(1).setCellValue("邮箱");
        row.createCell(2).setCellValue("年龄");
        List<Employee> employees = employeeMapper.selectAll();
        for (int i = 0; i < employees.size(); i++) {
            Employee employee = employees.get(i);
            //创建行
            row = sheet.createRow(i + 1);
            //设置内容到单元格中
            row.createCell(0).setCellValue(employee.getName());
            row.createCell(1).setCellValue(employee.getEmail());
            row.createCell(2).setCellValue(employee.getAge());
        }
        return wb;
    }

    /**
     * 导入excel
     * @param file
     * @throws IOException
     */
    @Override
    public void importXls(MultipartFile file) throws IOException {
        //把接收到的文件以excel的方式去读取并操作
        Workbook wb = new HSSFWorkbook(file.getInputStream());
        //读取第一页
        Sheet sheet = wb.getSheetAt(0);
        //获取最后一行的索引
        int lastRowNum = sheet.getLastRowNum();
        //从索引为1的行数开始读(忽略标题行)
        for (int i = 0; i <= lastRowNum; i++) {
            //获取行数据
            Row row = sheet.getRow(i);
            //获取用户姓名
            String name = row.getCell(0).getStringCellValue();
            //判断如果用户名是空，就不再往下读
            if (!StringUtils.hasLength(name.trim())) {
                return;
            }
            Employee employee = new Employee();
            employee.setName(name);
            employee.setEmail(row.getCell(1).getStringCellValue());
            employee.setAge(Integer.valueOf(row.getCell(2).getStringCellValue()));

            employee.setPassword("1");
            this.save(employee, null);

        }
    }

    @Override
    public List<Employee> selectByRoleSn(String... sns) {
        return employeeMapper.selectRolenSn(sns);
    }
}
